package es.udc.fic.hamNeggs.manager;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import es.udc.fic.hamNeggs.pojo.User;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Repository(value = "user")
public class UserManager extends AbstractManager {
    private final static Logger LOG = Logger.getLogger(UserManager.class.getName());

    @Transactional(readOnly = true)
    @SuppressWarnings("unchecked")
    public List<User> getUserList() {
        List<User> list = session.createQuery("from User where usr_name NOT LIKE 'admin'").list();

        Collections.sort(list,
                new Comparator<User>() {
                    public int compare(User o1, User o2) {
                        return o1.getId().intValue() - o2.getId().intValue();
                    }
                });
        return list;
    }

    @Transactional(readOnly = true)
    public User getUser(Long id) {
        return (User) session.get(User.class, id);
    }

    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public User getUser(String name) {
        List<Integer> userId = session.createSQLQuery("select usr_id from hamneggs.users where usr_name like '" + name + "';").list();
        if (userId == null || userId.isEmpty() || userId.get(0) == null)
            return null;
        return getUser(new Long(userId.get(0)));
    }

    @Transactional(readOnly = false)
    public void saveUser(User user) {
        super.save(user, LOG);
    }

    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public Integer validPasss(final String name, final String pass) {
        List<Integer> userId = session.createSQLQuery("select usr_id from hamneggs.users where usr_name like '" + name + "' and usr_pass like '" + org.springframework.util.DigestUtils.md5DigestAsHex(pass.getBytes()) + "';").list();
        if (userId == null || userId.isEmpty() || userId.get(0) == null)
            return null;
        return userId.get(0);
    }

    @Transactional(readOnly = false)
    public void deleteUser(User user) {
        super.delete(user, LOG);
    }

    @Transactional(readOnly = false)
    public void updateUser(User user) {
        super.update(user, LOG);
    }

}
